package com.example.demo.handler;

import com.example.demo.exception.LogoutFailedException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

public class MyLogoutHandler implements LogoutHandler {

    private final StringRedisTemplate stringRedisTemplate;

    public MyLogoutHandler(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String authorization = request.getHeader("Authorization");
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            throw new LogoutFailedException("Token格式错误");
        }
        String token = authorization.substring(7);
        if (!Boolean.TRUE.equals(stringRedisTemplate.delete("user:token:" + token))) {
            throw new LogoutFailedException("token不存在,请检查是否存在Authorities");
        }
    }
}
